package cn.xshi.oauth.client.publisher;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import cn.xshi.oauth.client.publisher.handler.NettyClientHandler;
/**
 * @Desc 服务器通道初始化
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
public class NettyClientInitializer extends ChannelInitializer<SocketChannel> {

    private NettyClient nettyClient;

    private String clientId;//客户端id（每个服务对应一个客户端唯一id）

    private String clientGroupId;//组Id（可以存多个服务共享一个组Id）

    /**
     *
     */
    public NettyClientInitializer(){

    }

    /**
     *
     * @param nettyClient
     * @param clientGroupId
     * @param clientId
     */
    public NettyClientInitializer(NettyClient nettyClient,String clientGroupId,String clientId){
        this.nettyClient = nettyClient;
        this.clientGroupId = clientGroupId;
        this.clientId = clientId;
    }

    /**
     *
     * @param socketChannel
     * @throws Exception
     */
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        //ProtobufVarint32LengthFieldPrepender，ProtobufVarint32FrameDecoder解决大字符串粘包、拆包问题
        socketChannel.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
        socketChannel.pipeline().addLast(new ProtobufVarint32FrameDecoder());
        socketChannel.pipeline().addLast(new ProtobufEncoder());
        socketChannel.pipeline().addLast("decoder", new StringDecoder());
        socketChannel.pipeline().addLast("encoder", new StringEncoder());
        socketChannel.pipeline().addLast(new NettyClientHandler(nettyClient,clientGroupId,clientId));
    }
}